package com.catietie.bookmanagement.service.Impl;

import com.catietie.bookmanagement.common.BaseContext;
import com.catietie.bookmanagement.common.result.PageResult;
import com.catietie.bookmanagement.dao.mapper.BookMapper;
import com.catietie.bookmanagement.dao.pojo.Book;
import com.catietie.bookmanagement.dto.req.BookListReqDTO;
import com.catietie.bookmanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    /**
     * 查看图书列表
     *
     * @param bookListReqDTO
     * @return
     */
    @Override
    public PageResult getAllBooks(Integer page, BookListReqDTO bookListReqDTO) {
        bookListReqDTO.setUsername(BaseContext.getCurrentUser());
        bookListReqDTO.setOffset((page - 1) * bookListReqDTO.getPageSize());
        List<Book> bookList = bookMapper.getBookList(bookListReqDTO);
        PageResult pageResult = new PageResult(bookList.size(), bookList);
        return pageResult;
    }

    @Override
    public void borrowBook(Integer bookId) {
        String username = BaseContext.getCurrentUser();
        Book book = Book.builder()
                .id(bookId)
                .borrowStatus(1)
                .borrowTime(LocalDateTime.now())
                .borrowUser(username)
                .build();
        bookMapper.update(book);
    }

    /**
     * 归还书籍
     *
     * @param bookId
     */
    @Override
    public void returnBook(Integer bookId) {
        String username = BaseContext.getCurrentUser();
        Book book = Book.builder()
                .returnTime(LocalDateTime.now())
                .id(bookId)
                .borrowUser(username)
                .borrowStatus(0)
                .build();
        bookMapper.update(book);
    }
}
